from pywinauto.application import Application
from utils.dbTreat import db
from utils.common import get_network_time
import utils.common as uc

import socket
from utils.paths import DATA_DIR


def connect_wx():
    """
    获取登录微信列表
    """
    process_ids = uc.find_process_id_by_name('WeChat.exe')
    if not process_ids:
        raise uc.WechatNotFoundError("未找到微信，请确认微信是否已启动！")
    try:
        for process_id in process_ids:
            app = Application(backend='uia').connect(process=process_id)
            try:
                # 获取微信名称
                bot_name = app.window(title="微信").child_window(control_type="ToolBar", title="导航").descendants()[
                    0].window_text()

                a = db.fetch_one("select * from bot where bot_name = ? and is_active = ?", (bot_name, 1))
                # 获取当前时间
                dataTime = get_network_time().strftime('%Y-%m-%d %H:%M:%S')
                if a is not None:
                    # print(f'已存在微信：{bot_name}')
                    # 更新微信信息
                    sqlText = """
                    update bot set pid=?, status = ?, login_time = ?, duration = ?, recv = ?, send = ?, update_time = ? where bot_name = ? and is_active = ?
                    """
                    db.execute(sql=sqlText,
                               params=(
                                   str(process_id), '运行中', str(dataTime), '0', '0', '0', str(dataTime), bot_name, 1))
                    # print(f'更新微信：{bot_name}')
                else:
                    # print(f'添加微信：{bot_name}')
                    sqlText = """
                        insert into bot (bot_name, pid, status, login_time, duration, recv, send, is_active, create_time, update_time) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                        """
                    db.execute(sql=sqlText, params=(
                        bot_name, str(process_id), '运行中', str(dataTime), '0', '0', '0', '1',
                        str(dataTime),
                        str(dataTime)))
                    # print(f'添加微信：{bot_name}')
            except:
                continue
    except:
        raise uc.WechatNotFoundError('微信连接异常')


def get_chat_session(bot_name, process_id):
    app = Application(backend='uia').connect(process=process_id)

    # 获取微信会话列表
    b_name = app.window(title="微信").child_window(control_type="List", title="会话").descendants(control_type="Button")

    dataTime = get_network_time().strftime('%Y-%m-%d %H:%M:%S')
    sessionBlackList = ["公众号", "小程序", "订阅号", "文件传输助手", "腾讯游戏安全中心", "QQ邮箱提醒", "微信游戏",
                        "QQ安全中心", "微信团队", "微信支付"]
    for i in b_name:
        # print(i.window_text())

        if i.parent().parent().window_text() in sessionBlackList:
            continue
        else:
            sqlBotGroupName = db.fetch_one("select * from bot_group where bot_name = ? and group_name = ?",
                                           (bot_name, i.window_text()))
            if sqlBotGroupName is None:
                sqlText = """
                insert into bot_group (bot_name, group_name, group_type, group_member_count, auth_type, auth_time, create_time, update_time) values (?, ?, ?, ?, ?, ?, ?, ?)
                """
                db.execute(sql=sqlText,
                           params=(bot_name, i.window_text(), '', 0, '', str(dataTime), str(dataTime), str(dataTime)))
                # print(f'添加群组：{i.window_text()}')

if __name__ == '__main__':
    # connect_wx()
    get_chat_session('Smile', 15652)
